package net.andersand.games.yatzy;

import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;

/**
 * A simple Yatzy implementation. Using "Swedish rules"
 * 
 * @author Anders Sandberg Nordbø
 */
public class Yatzy {

	static final int NUMBER_OF_DICES = 5;

	private Game game;

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int players = 0;
		if (args.length > 0) {
			try {
				players = Integer.parseInt(args[0]);
			} catch (NumberFormatException nfe) {
				System.out.println("The argument passed is not a valid number");
			}
		}
		new Yatzy(players);
	}

	/**
	 * Init the game and set up the GUI
	 */
	Yatzy(int players) {
		if (players == 0) {
			players = getNumberOfPlayersFromUser();
		}
		List<String> playerNames = new ArrayList<String>();
		// TODO should be used only when user cannot specify names
		for (int i=1; i<=players; i++) {			
			playerNames.add("Player " + i);
		}
		YatzyFrame frame = new YatzyFrame(playerNames);
		game = new Game(frame, playerNames);
		frame.setListener(game);
	}

	Yatzy() {
		this(0);
	}

	/**
	 * TODO Maybe the input dialog should ask for player names, not numbers
	 * @return number of players
	 */
	private int getNumberOfPlayersFromUser() {
		int numberOfPlayers = 0;
		String userInput = (String) JOptionPane.showInputDialog(null,
				"Welcome to Yatzy.\nPlease select number of players", "Yatzy",
				JOptionPane.INFORMATION_MESSAGE, null, new String[] { "1", "2",
						"3", "4", "5", "6", "7", "8", "9", "10" }, "2");
		if (userInput == null) {
			System.exit(0);
		}
		numberOfPlayers = Integer.parseInt(userInput);
		return numberOfPlayers;
	}
}
